// Describe: udp服务模块
package udp

import (
	"encoding/json"
	"fmt"
	"github.com/spf13/viper"
	"net"
	"wormhole/pkg/event"
	"wormhole/protos/hole"
)

// Dimple
//  @Description: 发送udp消息
//  @receiver s
//  @param address
//  @param event
//  @return error
func Dimple(ripple *hole.Ripple) error {
	address := fmt.Sprintf("%v:%v", ripple.Ip, ripple.Port)
	conn, err := net.Dial("udp", address)
	if err != nil {
		return err
	}
	defer conn.Close()
	message := UdpMessage{
		Ripple: &hole.Ripple{
			Ip:    viper.GetString("core.ip"),
			Name:  viper.GetString("core.name"),
			Port:  viper.GetInt32("core.port"),
			Event: ripple.Event,
		},
	}
	data, err := json.Marshal(message)
	_, err = conn.Write(data)
	if err != nil {
		return err
	}
	return nil
}

// Broadcast
//  @Description: 广播消息
//  @receiver s
//  @return error
func Broadcast() error {
	ripple := &hole.Ripple{
		Ip:    "255.255.255.255",
		Port:  viper.GetInt32("core.port"),
		Event: event.BroadcastEvent,
	}
	err := Dimple(ripple)
	if err != nil {
		return err
	}
	return nil
}

type UdpMessage struct {
	*hole.Ripple `json:"ripple"`
}
